from fastapi import APIRouter, HTTPException, BackgroundTasks
from fastapi.responses import StreamingResponse
from sse_starlette.sse import EventSourceResponse
import json
import logging
from typing import AsyncGenerator

from models.chat_models import ChatRequest, ChatResponse, TTSRequest
from services.chat_service import ChatService
from services.dashscope_service import DashScopeService
from backend.config.poets_knowledge import get_poet_voices, get_all_poets, get_poet_knowledge

logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter(prefix="/api", tags=["chat"])

# 初始化服务
chat_service = ChatService()
dashscope_service = DashScopeService()

@router.post("/chat", response_model=ChatResponse)
async def chat_with_ai(request: ChatRequest):
    """
    标准对话接口
    
    Args:
        request: 聊天请求
        
    Returns:
        ChatResponse: 完整的聊天响应
    """
    try:
        logger.info(f"收到对话请求: {request.message}")
        response = await chat_service.process_chat(request)
        return response
    except Exception as e:
        logger.error(f"对话处理失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"对话处理失败: {str(e)}")

@router.post("/chat/stream")
async def chat_stream(request: ChatRequest):
    """
    流式对话接口，支持Server-Sent Events
    
    Args:
        request: 聊天请求
        
    Returns:
        EventSourceResponse: 流式响应
    """
    async def generate_stream() -> AsyncGenerator[str, None]:
        try:
            async for chunk in chat_service.process_chat_stream(request):
                yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
        except Exception as e:
            logger.error(f"流式对话失败: {str(e)}")
            yield f"data: {json.dumps({'type': 'error', 'message': str(e)}, ensure_ascii=False)}\n\n"
    
    return EventSourceResponse(generate_stream())

@router.post("/tts")
async def text_to_speech(request: TTSRequest, background_tasks: BackgroundTasks):
    """
    文本转语音接口
    
    Args:
        request: TTS请求
        background_tasks: 后台任务
        
    Returns:
        dict: 包含音频URL和时长的响应
    """
    try:
        logger.info(f"收到TTS请求: {request.text[:50]}...")
        
        audio_url, duration = await dashscope_service.synthesize_speech(
            text=request.text,
            voice=request.voice
        )
        
        return {
            "audio_url": audio_url,
            "duration": duration,
            "text": request.text
        }
        
    except Exception as e:
        logger.error(f"TTS处理失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"语音合成失败: {str(e)}")

@router.get("/voices")
async def get_available_voices():
    """
    获取可用的诗人语音列表
    
    Returns:
        dict: 可用诗人语音列表
    """
    return {
        "voices": get_poet_voices()
    }

@router.post("/poet/switch/{poet_id}")
async def switch_poet(poet_id: str):
    """
    切换诗人角色
    
    Args:
        poet_id: 诗人ID
        
    Returns:
        dict: 切换结果
    """
    try:
        if poet_id not in get_all_poets():
            raise HTTPException(status_code=404, detail=f"诗人 {poet_id} 不存在")
        
        chat_service.set_poet(poet_id)
        poet_info = get_poet_knowledge(poet_id)
        
        return {
            "success": True,
            "current_poet": poet_id,
            "poet_info": {
                "name": poet_info.get("name"),
                "dynasty": poet_info.get("dynasty"),
                "style": poet_info.get("style")
            }
        }
    except Exception as e:
        logger.error(f"切换诗人失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"切换诗人失败: {str(e)}")

@router.get("/poet/current")
async def get_current_poet():
    """
    获取当前诗人信息
    
    Returns:
        dict: 当前诗人信息
    """
    current_poet = chat_service.get_current_poet()
    if not current_poet:
        return {"current_poet": None}
    
    poet_info = get_poet_knowledge(current_poet)
    return {
        "current_poet": current_poet,
        "poet_info": poet_info
    }

@router.get("/poets")
async def get_all_poets_info():
    """
    获取所有诗人信息
    
    Returns:
        dict: 所有诗人信息
    """
    poets = get_all_poets()
    poets_info = {}
    
    for poet_id in poets:
        poet_data = get_poet_knowledge(poet_id)
        poets_info[poet_id] = {
            "name": poet_data.get("name"),
            "dynasty": poet_data.get("dynasty"),
            "style": poet_data.get("style"),
            "personality": poet_data.get("personality"),
            "famous_works": poet_data.get("famous_works", [])[:3]  # 只返回前3个代表作
        }
    
    return {"poets": poets_info}

@router.post("/analyze/emotion")
async def analyze_emotion(text: str):
    """
    分析文本情绪和推荐动作
    
    Args:
        text: 要分析的文本
        
    Returns:
        dict: 情绪分析结果
    """
    try:
        emotion, animation = dashscope_service.analyze_emotion_and_action(text)
        return {
            "text": text,
            "emotion": emotion,
            "animation": animation
        }
    except Exception as e:
        logger.error(f"情绪分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"情绪分析失败: {str(e)}")